
package andre.grids.db;

import andre.grids.db.dataclasses.*;

import andre.grids.guids.IGuid;
import com.db4o.*;
import com.db4o.query.*;
import java.util.Iterator;
import java.util.regex.*;

/**
 *
 * @author andre
 */
public class DbFileQueries 
        extends DbQueries<DbFile> {
    
    public DbFile getByName(String fileName) {
        DbFile template = new DbFile();
        template.setFileName(fileName);
        
        DbFile[] result = getByTemplate(template);
        if (result == null)
            return null;
        return result[0];
    }
    
    private DbFile[] getByTemplate(DbFile template) {
        ObjectSet<DbFile> files = super.getObjectListByPrototype(template);
        
        if (files == null || files.size() == 0)
            return null;
        
        DbFile [] result = new DbFile[files.size()];
        
        Iterator<DbFile> filesIt = files.iterator();
        int x = 0;
        for(;filesIt.hasNext();)
            result[x++] = filesIt.next();
        
        return result;                
    }
    
    public DbFile[] getByGuid(IGuid guid) {
        DbFile template = new DbFile();
        template.setFileGuid(guid.toHexString());
        return getByTemplate(template);
    }
    
    public DbFile[] getByParent(String parentName) {
        DbDirectoryQueries query = new DbDirectoryQueries();
        DbDirectory dir = query.getDirByName(parentName);
        DbFile template = new DbFile();
        template.setParentDir(dir);
        ObjectSet<DbFile> files = super.getObjectListByPrototype(template);
        DbFile [] array = new DbFile[files.size()];
        Iterator<DbFile> it = files.iterator();
        int x = 0;
        for(;it.hasNext();)
            array[x++] = it.next();
        return array;
    }
    
    public DbFile[] listAll(String parent) {
        
        final Pattern exp = Pattern.compile(parent + (parent.endsWith("/")?"":"/") + ".*");
        
        ObjectSet<DbFile> files = super.getDb().getObjects().query(new Predicate<DbFile>() {
            public boolean match(DbFile arg) {
                Matcher match = exp.matcher(arg.getFileName());
                return match.matches();
            }
        });
        
        DbFile [] result = new DbFile[files.size()];
        Iterator<DbFile> it = files.iterator();
        int x = 0;
        for(;it.hasNext();)
            result[x++] = it.next();
        return result;
    }
    
}
